<?php
/**
 * Created by PhpStorm.
 * FileName: PayController.class.php
 * User: Administrator
 * Date: 2018/10/16
 * Time: 10:02
 */

namespace Api\Controller;

use Admin\Model\OrderModel;
use Admin\Model\UserModel;
use Org\Util\String;

class PayController extends ApiController {

    private $userModel;
    private $orderModel;

    public function __construct() {
        parent::__construct();
        $this->userModel = new UserModel();
        $this->orderModel = new OrderModel();
    }

    public function index() {
        $user_id = I('user_id');
        $trip_id = I('trip_id');
        $reward = I('reward',0);
        $deposit = I('deposit',0);
        $brokerage = I('brokerage',0);
        if (!$user_id || !$trip_id || $reward<0 || $deposit<0) {
            $this->callBack('无效的参数',$this->ERROR_CODE);
        }

        if ($this->getProcessBuyerOrderNum($user_id) >= $this->userLevelInfo['buyer_order_max']) {
            return $this->callBack('您的抢单数量已达上限！',$this->ERROR_CODE);
        }

        $openId = $this->userModel->where(array('id' => $user_id))->getField('openid');
        if (!$openId) {
            $this->callBack('无效的openId',$this->ERROR_CODE);
        }
        // 如果手续费小于等于0，则按预付款+报酬总和的1%来计算。
        if ($brokerage <= 0) {
            $brokerage = ($reward + $deposit) * 0.01;
        }
        $money = round($reward+$deposit+$brokerage,2);
        // 微信支付统一下单
        $outTradeNo = sprintf('bd_%s_%s_%s',$user_id,$trip_id,time());

        $unifiedOrder = $this->getUnifiedOrder($openId,$money,$outTradeNo);
        if ($unifiedOrder['return_code'] != 'SUCCESS') {
            $this->callBack($unifiedOrder['return_msg'],$this->ERROR_CODE);
        }
        if ($unifiedOrder['result_code'] != 'SUCCESS') {
            $this->callBack('无效的prepay_id',$this->ERROR_CODE,$unifiedOrder);
        }
        // 返回的参数中，只有当return_code和result_code两个字段的值都为SUCCESS时，才会有prepay_id字段
        $prepayId = $unifiedOrder['prepay_id'];
        $package = sprintf('prepay_id=%s',$prepayId);
        $nonceStr = String::randString(32);
        $paySign = $this->getPaySign($nonceStr,$package);
        $this->buildOrderData($outTradeNo,$prepayId);
        $data = array(
            'timeStamp' => time(),
            'nonceStr' => $nonceStr,
            'package' => $package,
            'signType' => 'MD5',
            'paySign' => $paySign,

        );
        return $this->callBack("支付参数",$this->SUCCESS_CODE,$data);
    }

    private function buildOrderData($outTradeNo,$prepayId) {
        $user_id = I('user_id');
        $trip_id = I('trip_id');
        $contact = I('contact');
        $type = I('type');
        $reward = I('reward');
        $deposit = I('deposit',0);
        $brokerage = I('brokerage',0);
        $remark = I('remark');
        $attache = I('attache');
        $removed = I('removed');
        $orderData = array(
            'user_id' => $user_id,
            'trip_id' => $trip_id,
            'contact' => $contact,
            'type' => $type,
            'reward' => $reward,
            'deposit' => $deposit,
            'brokerage' => $brokerage,
            'remark' => $remark,
            'attache' => $attache,
            'removed' => $removed,
            'form_id' => $prepayId
        );
        F($outTradeNo, json_encode($orderData));
    }

    // 微信支付统一下单
    private function getUnifiedOrder($openId,$money,$outTradeNo) {
        require_once dirname(__FILE__).'/../Wxpay/WxPay.Config.php';
        require_once dirname(__FILE__).'/../../../ThinkPHP/Library/Vendor/WxpayAPI/lib/WxPay.Api.php';
        try{
            $input = new \WxPayUnifiedOrder();
            $input->SetBody("帮带-行程订单");
            $input->SetOut_trade_no($outTradeNo);
            // 订单总金额，单位为分
            $input->SetTotal_fee($money*100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $input->SetNotify_url(C('wx_pay_notify_url'));
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openId);
            $config = new \WxPayConfig();
            $order = \WxPayApi::unifiedOrder($config, $input);
            return $order;
        } catch(\Exception $e) {
            $this->callBack($e->getMessage(),$this->ERROR_CODE);
        }
    }

    // 获取支付签名
    private function getPaySign($nonceStr,$package) {
        $signField = array(
            'appId' => 'wx429f7b71d46c2c49',
            'timeStamp' => time(),
            'nonceStr' => $nonceStr,
            'package' => $package,
            'signType' => 'MD5'
        );
        // 参数名按字典从小到大排序（即升序）
        ksort($signField);
        // 最后加入商户key参数
        $signField['key'] = '43210987659876543210zhangshengli';
        $signStr = $this->ToUrlParams($signField);
        $paySign = strtoupper(md5($signStr));
        return $paySign;
    }

    // 获取正在进行中的已抢订单数量
    private function getProcessBuyerOrderNum($user_id) {
        $count = $this->orderModel->where(array('buyer_id' => $user_id,'state' => array('in',array('0','1','2'))))->count();
        return $count;
    }

    private function ToUrlParams($array) {
        $buff = "";
        foreach ($array as $k => $v) {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }
        $buff = trim($buff, "&");
        return $buff;
    }

}